package level4.gemo
{
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.geom.Matrix;

	/**
	 * 补间动画,变换 管理
	 * 用于 进行改变 flash cs中导出的MovieClip的补间动画.
	 * */
	public class TweenAnimationTransformX
	{
		public function TweenAnimationTransformX()
		{
		}
		/**
		 * 将 新矩阵m,应用到mc的startFrame,endFrame间的补间动画上.
		 * @param startFrame : 开始帧
		 * @param endFrame   : 结束帧
		 * @param mc : 有时间轴动画的元件
		 * @param m : 新的矩阵
		 * */
		public function ApplyTransforms(startFrame:int,endFrame:int,tweenMc:MovieClip,targetMc:MovieClip,mat:Matrix):void{
			var mats:Array = storeTransforms(startFrame,endFrame,tweenMc,targetMc);
			appendTransform(mat,mats);
			//applyTransform(startFrame,endFrame,tweenMc,targetMc,mats);
			
			tweenMc.addEventListener(Event.ENTER_FRAME,loop);
			
			function loop(e:Event):void{
				if(!tweenMc.stage){
					tweenMc.removeEventListener(Event.ENTER_FRAME,loop);
				}
				var index:int = tweenMc.currentFrame - startFrame;
				var mat:Matrix = mats[index];
				trace(index,mat)
				if(mat){
					targetMc.transform.matrix = mat;
				}
			}
		}
		
		/**
		 * 1 保存原始的变换
		 * @param startFrame 开始帧
		 * @param endFrame 结束帧
		 * @param tweenMc ,补间动画的宿主元件
		 * @param targetMc,要获取变换信息的元件,即补间中控制的元件
		 * */
		public function storeTransforms(startFrame:int,endFrame:int,tweenMc:MovieClip,targetMc:MovieClip):Array{
			var originalFrame:int = tweenMc.currentFrame;
			
			var transforms:Array = [];
			for(var i:int = startFrame;i<=endFrame;i++){
				tweenMc.gotoAndStop(i);
				transforms.push(targetMc.transform.matrix);
			}
			tweenMc.gotoAndStop(originalFrame);
			return transforms;
		}
		
		/**
		 * 2 将mats数组中每个matrix都应用mat,实现变化的组合.
		 * @param mat 
		 * @param mats
		 * */
		public function appendTransform(mat:Matrix,mats:Array):void{
			for(var i:int = 0;i<mats.length;i++){
				mats[i].concat(mat);
			}
		}
		/**
		 * 3 应用组合过.新的变化
		 * @param startFrame
		 * @param endFrame
		 * @param tweenMc
		 * @param targetMc
		 * @param mats
		 */
		public function applyTransform(startFrame:int,endFrame:int,tweenMc:MovieClip,targetMc:MovieClip,mats:Array):void{
			var originalFrame:int = tweenMc.currentFrame;
			var matIndex:int = 0;
			for(var i:int = startFrame;i<endFrame;i++){
				tweenMc.gotoAndStop(i);
				matIndex = i-startFrame;
				matIndex = matIndex > 0? matIndex : 0;
				targetMc.transform.matrix = mats[matIndex];
			}
			tweenMc.gotoAndStop(originalFrame);
		}
	}
}